package com.ys.service.sys.impl;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import com.bo.enume.sys.StatusEnum;
import com.ys.dto.RowClickGridConfigDto;
import com.ys.entity.shiro.LoginUser;
import com.ys.entity.sys.YsButton;
import com.ys.entity.sys.YsButtonItem;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsDict;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsRowClickGrid;
import com.ys.entity.sys.YsRowClickGridCol;
import com.ys.enume.sys.YsButtonEnum;
import com.ys.enume.sys.YsColEnum;
import com.ys.enume.sys.YsMenuEnum;
import com.ys.mapper.business.CommonMapper;
import com.ys.mapper.sys.SysCommonMapper;
import com.ys.service.sys.CommonService;
import com.ys.util.admin.GridUtil;
import com.ys.util.admin.RowClickGridUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;
import com.ys.vo.W;

@Service("commonService")
public class CommonServiceImpl implements CommonService {

//	@Autowired
	@Resource
	private CommonMapper commonMapper;
	
	@Resource
	private SysCommonMapper sysCommonMapper;
	
	@Override
	public String indexCommonOfMenu(Model model,
    		HttpServletRequest request,
    		Long menuId,
    		Map<String, String> initCondCodeValue) {
		
		LoginUser loginUser = ShiroUtils.getLoginUser();
		
		YsMenu entity = new YsMenu().setId(menuId).queryFirst();
		if (entity == null) {
			return W.error(model, "页面不存在");
		}
		
		String pathGridRequest = entity.getPathGridRequest();
		String pathGridEditRequest = entity.getPathGridEditRequest();
		String pathGridExportRequest = entity.getPathGridExportRequest();
		
		GridDto.MenuDto menu = null;
		{
			String title = entity.getName();
			menu = new GridDto.MenuDto(title, pathGridRequest, pathGridEditRequest, pathGridExportRequest);
		}
		
		List<YsCol> listYsCol = new YsCol()
				.setMenuId(menuId)
				.setOrderby("A.SortNo asc")
				.queryList();
		
		// dictKey-List<SysDict>的MAP
		Map<String, List<YsDict>> KEY_LISTDICT_MAP = new HashMap<String, List<YsDict>>();
		List<YsDict> listYsDict = new YsDict()
				.where("A.DictKey in (select DictKeyBase from YS_Col where MenuId = " + menuId + ")")
				.setOrderby("A.DictKey asc,A.SortNo asc")
				.queryList();
		for(YsDict ysDict : listYsDict) {
			String dictKey = ysDict.getDictKey();
			if (KEY_LISTDICT_MAP.containsKey(dictKey)) {
				KEY_LISTDICT_MAP.get(dictKey).add(ysDict);
			} else {
				List<YsDict> listValue = new ArrayList<YsDict>();
				listValue.add(ysDict);
				KEY_LISTDICT_MAP.put(dictKey, listValue);
			}
		}
		List<GridDto.ColGridDto> colGridArr;
		try {
			colGridArr = GridUtil.listColumn(listYsCol, entity, KEY_LISTDICT_MAP);
		} catch (Exception e) {
			e.printStackTrace();
			return W.error(model, e.getMessage());
		}

		// 工具栏
		GridDto.ToolbarDto toolbar = null;
		{
			Long loginRoleId = loginUser.getRoleId();
			List<YsButton> listYsButton = new YsButton()
					.setMenuId(menuId)
					.where(loginRoleId == 1L ? "1=1" : "A.Id in (select ButtonId from YS_RoleButton where RoleId = " + loginRoleId + ")")
					.setOrderby("A.SortNo asc").setStatus(StatusEnum.ON_USED.value)
					.queryList();
			List<GridDto.ToolbarDto.ButtonDto> buttonArr = new ArrayList<GridDto.ToolbarDto.ButtonDto>();
			for(YsButton btn : listYsButton) {
				Integer type = btn.getType();
				String name = btn.getName();
				String event = btn.getEvent();
				String icon = btn.getIcon();
				String style = YsButtonEnum.StyleType.getNameStyle(btn.getStyleType());
				buttonArr.add(new GridDto.ToolbarDto.ButtonDto(type, name, event, icon, style));
			}
			
			
			toolbar = new GridDto.ToolbarDto(buttonArr);
		}

//		List<String> displayHtmls = new ArrayList<String>();
		List<GridDto.ConditionDto> conditions = GridUtil.listCondition(listYsCol, initCondCodeValue);
//		// 是否统计
//    	if (sysMenu.getIsShowCount() == MenuEnum.ShowCount.YES.value) {
//    		StringBuffer sb = new StringBuffer().append("")
//	    		.append("<div class='layui-inline'>")
//	    			.append("<input type='checkbox' name='isCount' title='统计'>")
//	    		.append("</div>");
//    		displayHtmls.add(sb.toString());
//		}
		
//		String primaryKey = entity.getDataBaseTable().startsWith("YS_") ? "id" : "guid";
		String primaryKey = "id";
		String templateType = entity.getTempletType();
		
		// 行单击列表配置
		RowClickGridConfigDto rowClickGridConfigDto = null;
		{
			Long rowClickGridId = entity.getRowClickGridId();
			if (rowClickGridId != null && rowClickGridId.longValue() != 0L) {
				YsRowClickGrid ysRowClickGrid = new YsRowClickGrid().setId(rowClickGridId).queryFirst();
				List<YsRowClickGridCol> listYsRowClickGridCol = new YsRowClickGridCol().setRowClickGridId(rowClickGridId)
						.setOrderby("A.SortNo asc")
						.queryList();
				rowClickGridConfigDto = RowClickGridUtil.getRowClickGridConfigDto(ysRowClickGrid, listYsRowClickGridCol);
			}
		}
		GridDto dto = new GridDto(menuId, primaryKey, menu, GridUtil.ColGridToString(colGridArr), toolbar, conditions, templateType, rowClickGridConfigDto,rowClickGridConfigDto!=null?rowClickGridConfigDto.getColArr():null);
		model.addAttribute("dto", dto);
//		if (sysMenu.getTypeTemplet() == SysMenuEnum.TypeTemplet.LIST_NORMAL.value) {
//			return "sys/common/templet_list";
//		} else if (sysMenu.getTypeTemplet().intValue() == SysMenuEnum.TypeTemplet.TREE_WITH_LIST.value) {
//			return "sys/common/templet_tree_with_list_normal";
//		} else if (sysMenu.getTypeTemplet().intValue() == SysMenuEnum.TypeTemplet.DIY.value) {
//			return sysMenu.getPathDiy();
//		} else if (sysMenu.getTypeTemplet().intValue() == SysMenuEnum.TypeTemplet.TREE_WITH_IFRAME.value) {
//			return "sys/common/templet_tree_iframe";
//		}
		
		String templetType = entity.getTempletType();
		
		if(templetType == null || templetType.length() == 0 || templetType.equals("none")) {
			return W.error(model, "尚未设置模板类型");
		}
//		else if (YsMenuEnum.TempletType.TREE_WITH_LIST.value.equals(templetType)) {
//			return "sys/common/templet_tree_with_list_normal";
//		} else if (YsMenuEnum.TempletType.SELF_DEFINE.value.equals(templetType)) {
//			System.out.println(infoJO.getString("pathSelfDefine"));
//			return infoJO.getString("pathSelfDefine");
//		}
        return entity.getTempletPath();
	}
	
	@Override
	public String indexCommonOfMenuBS(Model model,
    		HttpServletRequest request,
    		Long menuId,
    		Map<String, String> initCondCodeValue) {

		if (menuId == null) {
			return W.error(model, "菜单ID不能为空");
		}
		YsMenu entity = new YsMenu().setId(menuId).queryFirst();
		if (entity == null) {
			return W.error(model, "页面不存在");
		}
		
		if (YsMenuEnum.TempletType.SELF_DEFINE.value.equals(entity.getTempletType())) {
			return entity.getTempletPath();
		}
		String pathGridRequest = entity.getPathGridRequest();

		// 条件字段
		List<IndexCommonOfMenuBSDto.ConditionDto> conditionArr = new ArrayList<IndexCommonOfMenuBSDto.ConditionDto>();
		List<YsCol> listYsCol = new YsCol().setMenuId(menuId)
				.setOrderby("A.SortNo asc")
				.queryList();
		for(YsCol ysCol : listYsCol) {
			
			if (ysCol.getFrontConditionState().equals(YsColEnum.FrontConditionState.YES.value)) {
				
				Long id = ysCol.getId();
				String conditionCode = ysCol.getFrontConditionCode();
				String code = conditionCode != null && conditionCode.length() > 0 ? conditionCode : ysCol.getCode();
				String type = ysCol.getFrontType();
				String rangeType = ysCol.getFrontConditionRangeType();
				String name = ysCol.getName();
				String value = ysCol.getFrontConditionDefault();
				
				if (value != null && value.length() > 0
						&& ("_ys_condition_latest_two_day".equals(value) || "_ys_condition_current_year".equals(value))) {
					value = null;
				}
				String dictKeyBase = ysCol.getDictKeyBase();
				conditionArr.add(new IndexCommonOfMenuBSDto.ConditionDto(id, code, type, rangeType, name, value, dictKeyBase));
			}
		}
		
		// 按钮数组
		List<IndexCommonOfMenuBSDto.ButtonDto> buttonArr = new ArrayList<IndexCommonOfMenuBSDto.ButtonDto>();
		List<YsButton> listYsButton = new YsButton().setMenuId(menuId).queryList();
		for(YsButton ysButton : listYsButton) {
			Integer type = ysButton.getType();
			String name = ysButton.getName();
			String event = ysButton.getEvent();
			String icon = ysButton.getIcon();
			String style = YsButtonEnum.StyleType.getNameStyle(ysButton.getStyleType());
			List<IndexCommonOfMenuBSDto.ButtonDto.ItemDto> itemArr = new ArrayList<IndexCommonOfMenuBSDto.ButtonDto.ItemDto>();
			List<YsButtonItem> listYsButtonItem = new YsButtonItem().setPid(ysButton.getId()).queryList();
			for(YsButtonItem ysButtonItem : listYsButtonItem) {
				String name2 = ysButtonItem.getName();
				String event2 = ysButtonItem.getEvent();
				String icon2 = ysButtonItem.getIcon();
				itemArr.add(new IndexCommonOfMenuBSDto.ButtonDto.ItemDto(name2, event2, icon2));
			}
			buttonArr.add(new IndexCommonOfMenuBSDto.ButtonDto(type, name, event, icon, style, itemArr));
		}
		
		// 字段数组
		List<IndexCommonOfMenuBSDto.ColDto> colArr = new ArrayList<IndexCommonOfMenuBSDto.ColDto>();
		for(YsCol ysCol : listYsCol) {
			Long id = ysCol.getId();
			Integer frontShow = ysCol.getFrontShow();
			boolean stateEdit = ysCol.getFrontEdit() != null && ysCol.getFrontEdit() == 1;
			String title = ysCol.getName();
			String field = ysCol.getCode();
			String type = ysCol.getFrontType();
			String fixed = YsColEnum.FrontFixed.getLayerFiexd(ysCol.getFrontFixed());
			Integer width = ysCol.getFrontWidth();
			String align = YsColEnum.FrontAlign.getLayerAlign(ysCol.getFrontAlign());
			boolean sort = true;
			String dictKeyBase = ysCol.getDictKeyBase();
			String templet = "";
			colArr.add(new IndexCommonOfMenuBSDto.ColDto(id, frontShow, stateEdit, title, field, type, fixed, width, align, sort, dictKeyBase, templet));
		}
		
		IndexCommonOfMenuBSDto dto = new IndexCommonOfMenuBSDto(menuId, pathGridRequest, conditionArr, buttonArr, colArr);
		model.addAttribute("js", "/static/js/grid/" + menuId + ".js");
		model.addAttribute("dto", dto);
		return "sys/common2/templet_list";
//        return entity.getTempletPath();
	}

	@Override
	public R editOnTable(HttpServletRequest request) {
		
		// 字段-值的MAP
		Map<String, String> paramMap = new HashMap<String, String>();
		Enumeration<String> reqNames = request.getParameterNames();
		for (; reqNames.hasMoreElements();) {
			String key = reqNames.nextElement();
			System.out.println(key + "=====" + request.getParameter(key));
			
			paramMap.put(key, request.getParameter(key));
		}

		// 单独处理：sys_menu_id
		String KEY_MENU_ID = "menuId";
		if (!paramMap.containsKey(KEY_MENU_ID) || paramMap.get(KEY_MENU_ID) == null || paramMap.get(KEY_MENU_ID).length() == 0) {
			return R.error("菜单ID不能为空");
		}
		String tableName = commonMapper.getDataBaseTableByMenuId(Long.parseLong(paramMap.get(KEY_MENU_ID)));
		paramMap.remove(KEY_MENU_ID);
		

		// 单独处理键：id
		String KEY_PK = "id";
		if (!paramMap.containsKey(KEY_PK) || paramMap.get(KEY_PK) == null || paramMap.get(KEY_PK).length() == 0) {
			return R.error("主键ID不能为空");
		}
		String pkValue = paramMap.get(KEY_PK);
		paramMap.remove(KEY_PK);
		
		if (KEY_PK.equals("guid")) {
			commonMapper.updateByMap(paramMap, tableName, pkValue);
		} else {
			commonMapper.updateByMapOfId(paramMap, tableName, Long.parseLong(pkValue));
		}
		
		return R.ok("修改成功");
	}
}
